package main

import (
	"activity_srv/model"
	"encoding/json"
	"fmt"
	"github.com/robfig/cron"
	"go.uber.org/zap"
	"log"
	MSMQ "smart-health-platforms/inits"
	"smart-health-platforms/pkg"
	"smart-health-platforms/untils"
)

func main() {
	rabbitmq := MSMQ.NewRabbitMQSimple("" +
		"2301a")
	simple, _ := rabbitmq.ConsumeSimple()
	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range simple {
			//消息逻辑处理，可以自行设计逻辑
			var seckillOrders model.SeckillOrder
			err := json.Unmarshal(d.Body, &seckillOrders)
			if err != nil {
				pkg.Error("反序列化失败", zap.Error(err))
				return
			}
			err = seckillOrders.CreateSeckillOrder()
			if err != nil {
				pkg.Error("创建订单失败", zap.Error(err))
				return
			}
			pkg.Info("创建订单成功")
			log.Printf("Received a message: %s", d.Body)
			SyncSeckillOrder(int(seckillOrders.SeckillGoodId), int(seckillOrders.Id))
		}
	}()
	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func SyncSeckillOrder(seckillGood, seckillOrder int) {
	c := cron.New()
	spec := "*/5 * * * * *"
	spec2 := "0 */2 * * * *"
	err := c.AddFunc(spec, func() {
		var seckillGoods model.SeckillGood
		seckillGoods.Id = uint(seckillGood)
		seckillGoods.StockCount = uint(untils.GetSeckillStock(int(seckillGoods.Id)))
		err := seckillGoods.UpdateSeckillGood()
		if err != nil {
			log.Printf("更新秒杀商品失败")
			return
		}
		log.Printf("更新秒杀商品成功")
	})

	err = c.AddFunc(spec2, func() {
		var seckillOrders model.SeckillOrder
		seckillOrders.Id = uint(seckillOrder)
		err = seckillOrders.GetSeckillOrderById()
		if err != nil {
			err = fmt.Errorf("获取订单信息失败")
			return
		}
		if seckillOrders.OrderStatus == 1 {
			err = seckillOrders.DeleteSeckillOrder()
			if err != nil {
				log.Printf("删除订单失败")
				return
			}
			untils.ReturnSeckillStock(int(seckillOrders.SeckillGoodId))
		}
		log.Println("返回库存成功")
	})
	fmt.Println(err)
	c.Start()

	select {}
}
